App.controller('menuController', ['$rootScope', '$scope', 'Page', function($rootScope, $scope, Page) {

    $scope.tree_data = [];

    $scope.query = function() {
        Page.ajaxPost('menu/treeGrid.do', null, function(resp) {
            $scope.menus = resp.data;
            $scope.menus2 = [];// 编辑时下拉
            $(resp.data).each(function(i, menu) {
                if (menu.menuType == '0') {// 菜单
                    $scope.menus2.push(menu);
                }
            });
        });
    }

    function getMenu(menu, menuId) {
        if (angular.isArray(menu)) {
            for (var i = 0, len = menu.length; i < len; i++) {
                var obj = getMenu(menu[i], menuId);
                if (obj) {
                    return obj;
                }
            }
        } else if (menu.menuId == menuId) {
            return menu;
        } else if (menu.children){
            var obj = getMenu(menu.children, stateName);
            if (obj) {
                return obj;
            }
        }
        return null;
    }

    $scope.query();

    $scope.deleteMenu = function (menu) {
        Page.confirm("确定要删除吗？", function() {
            Page.ajaxPost('menu/delete.do', menu, function() {
                $scope.query();
            });
        });
    };
    // 编辑
    $scope.editMenu = function (row) {
        $scope.menu = row;
        // 下拉树赋值
        $scope.menu.parentMenu = row.parentMenuId;
        $scope.edit = true;
    };

    $scope.save = function() {
        Page.ajaxPost($scope.menu.menuId ? 'menu/update.do' : 'menu/add.do', $scope.menu, function() {
            $scope.edit = false;
            $scope.query();
        });
    };

    // 取消编辑
    $scope.cancel = function () {
        $scope.edit = false;
        $scope.menu = {};
    };

    // 新增
    $scope.addMenu = function () {
        $scope.edit = true;
        $scope.showMenuType = true;
        $scope.menu = {menuType: '0', menuState: '1'};// 默认为菜单
    };

    // 切换上级菜单
    $scope.$watch('menu.parentMenuId', function(newValue, oldValue) {
        if (angular.isDefined(newValue)) {
            var child = null;
            $($scope.menus).each(function(i, menu) {
                if (menu.parentMenuId == newValue) {
                    child = menu;
                    return false;
                }
            });
            if (child) {
                $scope.menu.menuType = child.menuType;
                $scope.showMenuType = false;
            } else {
                $scope.menu.menuType = '0';// 默认为菜单
                $scope.showMenuType = true;
            }
        }
    });

    $scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) {
        $("#menu_table").treetable({ expandable: true }, true);
    });
}]);
